package com.test.ll;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyFile {
	public static void main(String[] args){
		String srcFile="D:\\source\\";
		String targetFile="D:\\target\\";
		
		deletefile(targetFile);	
		copySingleFile(srcFile,targetFile);
		
	}
	
	public static void deletefile(String path){
		File file = new File(path);
		File temp=null;
		String[] filelist=file.list();
//		System.out.println(filelist.length);
		for(int i=0;i<filelist.length;i++){
			temp=new File(path+File.separator+filelist[i]);		
			System.out.println("已删除"+temp);
			temp.delete();
			if(temp.isDirectory()){
				System.out.println("已删除"+temp);
				deletefile(path+"\\"+filelist[i]);
				
				temp.delete();
			}
		}
	}
	
	public static void copySingleFile(String srcFile,String targetFile){
		File file = new File(srcFile);
		String target=targetFile;
		File temp= null;
		String a="";
		String[] filelist = file.list();
		//判断源目录和备份目录是否一致；
		if(srcFile!=targetFile){
			//判断源目录是否存在
			if(!file.exists()){
				System.out.println(srcFile+"源目录不存在");
				System.exit(0);
			}else{
				//遍历整个目录
				for(int i=0;i<filelist.length;i++){
					//判断路径不是目录
					if(!(temp=new File(srcFile+File.separator+filelist[i])).isDirectory()){
					System.out.println("源文件"+temp);
					target=targetFile+File.separator+temp.getName();
					
					try{
						//写入文件
						FileReader fr= new FileReader(temp);
						BufferedReader br = new BufferedReader(fr);
						FileWriter fw = new FileWriter(target);
						BufferedWriter bw = new BufferedWriter(fw);
						while((a=br.readLine())!=null){
							bw.write(a);
							bw.flush();
							
						}
						System.out.println("复制文件成功"+target);
						fr.close();
						br.close();
						fw.close();
						bw.close();
						
					}catch(FileNotFoundException fnfe){
						System.out.println("没找到文件");
					}catch(IOException io){
						io.printStackTrace();
					}
					}else{
						//开始创建目录
						//获得需要创建目录的地址
						temp=new File(targetFile+File.separator+filelist[i]);
						
						//把下一个目录的值赋值给srcFile,为了重新调用该方法
						srcFile=srcFile+File.separator+filelist[i];
						temp.mkdir();
						System.out.println("创建目录"+temp);
						//System.out.println(srcFile+"*****targetFile");
						
						copySingleFile(srcFile, String.valueOf(temp));
					}
				}
			}
		}else{
			System.out.println("源目录和备份目录一致，不能复制！");
			System.exit(0);
		}
	}
}
